// matchDetail.js
const dbUtil = require('../interface/interfaceData-list'); // 引入封装好的数据库工具函数
const db = wx.cloud.database();
Page({
  data: {
    match: {}
  },

  onLoad: function (options) {
    const matchId = options.id;
    this.fetchMatchDetails(matchId);
  },

  fetchMatchDetails: async function (matchId) {
    try {
      const result = await dbUtil.getDataWhere('team', { id: matchId });
      if (result.length > 0) {
        this.setData({
          match: result[0]
        });
      }
    } catch (error) {
      console.error(error);
    }
  },

  bindLeftScoreInput(e) {
    this.setData({
      'match.leftscore': parseInt(e.detail.value)
    });
  },

  bindRightScoreInput(e) {
    this.setData({
      'match.rightscore': parseInt(e.detail.value)
    });
  },

  bindStatusInput(e) {
    this.setData({
      'match.status': e.detail.value
    });
  },

  bindLeftField0Input(e) {
    this.setData({
      'match.leftfields[0]': parseInt(e.detail.value)
    });
  },

  bindLeftField1Input(e) {
    this.setData({
      'match.leftfields[1]': parseInt(e.detail.value)
    });
  },

  bindLeftField2Input(e) {
    this.setData({
      'match.leftfields[2]': parseInt(e.detail.value)
    });
  },

  bindLeftField3Input(e) {
    this.setData({
      'match.leftfields[3]': parseInt(e.detail.value)
    });
  },

  bindLeftField4Input(e) {
    this.setData({
      'match.leftfields[4]': parseInt(e.detail.value)
    });
  },

  bindRightField0Input(e) {
    this.setData({
      'match.rightfields[0]': parseInt(e.detail.value)
    });
  },

  bindRightField1Input(e) {
    this.setData({
      'match.rightfields[1]': parseInt(e.detail.value)
    });
  },

  bindRightField2Input(e) {
    this.setData({
      'match.rightfields[2]': parseInt(e.detail.value)
    });
  },

  bindRightField3Input(e) {
    this.setData({
      'match.rightfields[3]': parseInt(e.detail.value)
    });
  },

  bindRightField4Input(e) {
    this.setData({
      'match.rightfields[4]': parseInt(e.detail.value)
    });
  },

  bindLeftPlayerScoreInput(e) {
    const index = e.currentTarget.dataset.index;
    const newScore = parseInt(e.detail.value);
    const leftPlayers = this.data.match.leftplayers;
    leftPlayers[index].score = newScore;
    this.setData({
      'match.leftplayers': leftPlayers
    });
  },

  bindRightPlayerScoreInput(e) {
    const index = e.currentTarget.dataset.index;
    const newScore = parseInt(e.detail.value);
    const rightPlayers = this.data.match.rightplayers;
    rightPlayers[index].score = newScore;
    this.setData({
      'match.rightplayers': rightPlayers
    });
  },

  submitChanges: async function () {
    const matchId = this.data.match.id+"";
    const updatedMatch = this.data.match;
    // 过滤掉不需要的字段
    const filteredMatch = JSON.parse(JSON.stringify(updatedMatch));
    delete filteredMatch._openid; // 删除 _openid 字段
    delete filteredMatch._id; // 删除 _id 字段
    console.log('Filtered Match:', filteredMatch);

    try {
      // 先查询文档是否存在
      const queryResult = await db.collection('team').where({ id: matchId }).get();
      if (queryResult.data.length === 0) {
        wx.showToast({
          title: '文档不存在',
          icon: 'none',
          duration: 2000
        });
        return;
      }

      console.log('Query Result:', queryResult);

      const result = await db.collection('team').doc(queryResult.data[0]._id).update({
        data: filteredMatch
      });

      console.log('Update result stats:', result.stats);
      if (result.stats.updated === 1) {
        wx.showToast({
          title: '修改成功',
          icon: 'success',
          duration: 2000
        });
      } else {
        wx.showToast({
          title: '修改失败',
          icon: 'none',
          duration: 2000
        });
      }
    } catch (error) {
      console.error('Update error:', error);
      wx.showToast({
        title: '修改失败',
        icon: 'none',
        duration: 2000
      });
    }
  }
});